<?php
namespace Common\Model;

use Think\Model;

class UserModel extends Model
{

    protected $trueTableName = 'user';

    protected $_map = array(
        'UserName' => 'name', // 把表单中name映射到数据表的username字段
        'PassWord' => 'password', // 把表单中的mail映射到数据表的email字段
    );

    protected $_validate = array(
        array('UserName', 'require', '用户名不能为空'),
        array('name', '', '用户名已经存在！', 0, 'unique', 1),
        array('PassWord', 'require', '密码不能为空'),
        array('PassWord1', 'require', '重复密码不能为空'),
    );

    public function getUserByName($name)
    {
        $map['name'] = array('eq', $name);
        $res = $this->where($map)->find();
        return $res;
    }


    public function getList()
    {
        $p = I('p', 0, 'int');
        $limit = C('DEFALUT_PAGE_SIZE');
        $startNum = $p > 0 ? ($p - 1) * $limit : 0;
        $count = $this->field("count(*) as count")->find();
        $data = $this->limit($startNum, $limit)->select();
        return array(
            'count' => $count['count'],
            'data' => $data
        );
    }

    public function addUser()
    {
        if (!$this->create()) {
            return false;
        } else {
            if (I('PassWord') != I('PassWord1')) {
                $this->error = "两次密码不一致";
                return false;
            }
            //
            $data['name'] = I('UserName');
            $data['reg_ip'] = get_client_ip();
            $data['password'] = md5(I('PassWord') .  C('PASSWORD_KEY'));
            $data['create_time'] = date('Y-m-d H:i:s', time());
            $this->add($data);
            return true;
        }
    }

    public function LoginCheck()
    {
        $post = I("post.");
        if (!empty($post['userName']) && !empty($post['passWord'])) {
            $user = $this->where("name = '{$post['userName']}'")->field("name,password,id")->find();
            if ($user) {
                if ($user['password'] == md5($post['passWord'] . C('PASSWORD_KEY'))) {
                    $key = sprintf('%s_uid', C('COOK_LOGIN_KEY'));
                    $value = $user['id'] . '_' . $user['name'] . "_" . md5($user['name'] . $user['password'] . C('PASSWORD_KEY'));
                    $sValue = $user['id'] . '_' . $user['name'] . "_" . $user['password'];
                    $user['last_login'] = time();
                    $this->save($user);
                    $_SESSION[$value] = $sValue;
                    cookie($key, $value, time() + 3600 * 24 * 7);
                    return true;
                } else {
                    $this->error = "用户名密码不匹配";
                    return false;
                }
            } else {
                $this->error = "用户名不存在";
                return false;
            }
        } else {
            $this->error = "用户密码不正确";    //用户密码不能为空
            return false;
        }
    }

    public function getUserById($uid)
    {
        $userInfo = $this->where("id = {$uid}")/*->field('id,name,face,phone,qq,weichat,email,describe,address,create_time,reg_ip,last_login,login_ip') */
        ->find();
        if ($userInfo) {
            return $userInfo;
        } else {
            return array();
        }
    }

    public function editPassword()
    {
        if (empty(I('newPassWord') || empty(I('oldPassWord')))) {
            $this->error = '密码不能为空';
            return false;
        }
        if (I('newPassWord') != I('newPassWord1')) {
            $this->error = '新密码不一致';
            return false;
        }
        $user = cookie(C('COOK_LOGIN_KEY'));
        if ($user) {
            $userId = explode('_', $user)[0];
            $userInfo = $this->getUserById($userId);
            if (isset($userInfo['password']) && $userInfo['password'] == md5(I('oldPassWord') . C('PASSWORD_KEY'))) {
                $userInfo['password'] = md5(I('newPassWord') . C('PASSWORD_KEY'));;
                $res = $this->save($userInfo);
                return $res;
            } else {
                $this->error = '旧密码不正确';
                return false;
            }
        } else {
            cookie(C('COOK_LOGIN_KEY'), null);
            $this->error = '登录超时请登录后操作';
            return false;
        }
    }

    public function edit()
    {
        $data = I('post.');
        $data['id'] = I('get.id');
        $user = $this->find($data['id']);
        if ($user['password'] != $data['password']) {
            $data['password'] = md5($data['password'] . C('PASSWORD_KEY'));
        }
        $this->save($data);
        return true;
    }

    public function editUserInfo($userId)
    {
        $data['id'] = $userId;
        $data['user_name'] = I('name');
        $data['face'] = I('pic');
        $data['phone'] = I('tel');
        $data['qq'] = I('qq');
        $data['weichat'] = I('wx');
        $data['email'] = I('email');
        $data['describe'] = I('email');
        $data['address'] = I('about');
        $res = $this->save($data);
        return true;
    }
}
